//引入express模块
const express = require('express');
const cors = require('cors')
//引入数据库连接模块
const pool = require('../pool.js');
//创建路由器对象
const r = express.Router();
//添加路由
const jwt = require('jsonwebtoken');
// const { id } = require('element-plus/es/locale/index.js');
const secret = "secret";
const exp = '1800s';


// 添加订单
r.post('/addorder', (req, res, next) => {
    let sqlstr = ''
    let keys = Object.keys(req.body);
    keys.forEach((key, index) => {
        if (key == 'other' || key == 'buygoodsUrl' || key == 'goodsimg') {
            let jsonString = JSON.stringify(req.body[key]);
            sqlstr += `${key}=${jsonString}`;
        } else {
            sqlstr += `${key}='${req.body[key]}'`;
        }

        // 如果当前不是最后一个字段，添加逗号
        if (index < keys.length - 1) {
            sqlstr += ',';
        }
    });

    const mysql = `insert into lutian_order set ${sqlstr}`;
    pool.query(mysql, (err, r) => {
        if (err) {
            next(err)
            return;
        } else {
            res.send({ code: 200, msg: '添加成功', data: r });
        }

    })

})

// 根据条件查询订单
r.get('/saveOrderlist', (req, res, next) => {
    let userId = req.query.userId;
    let keyword = req.query.keyword;
    let buygoodsDate = req.query.buygoodsDate;
    let shippingDate = req.query.shippingDate;
    let expressNum = req.query.expressNum
    let specialtype = req.query.specialtype
    let pagesize = req.query.pagesize;
    let currentpage = req.query.currentpage - 1;
    let sqlstr = 'select * from lutian_order'
    let sqlstr2 = 'select * from lutian_order'
    let sqlarr = []
    if (keyword != '' && keyword != undefined) {
        sqlarr.push(`(goodsName LIKE '%${keyword}%' OR address LIKE '%${keyword}%' OR logistics LIKE '%${keyword}%' OR storename LIKE '%${keyword}%')`)
    }
    if (userId != '' && userId != undefined) {
        sqlarr.push(`userId = ${userId}`)
    }
    if (buygoodsDate != '' && buygoodsDate != undefined) {
        sqlarr.push(`buygoodsDate = ${JSON.stringify(buygoodsDate)}`)
    }
    if (shippingDate != '' && shippingDate != undefined) {
        sqlarr.push(`shippingDate = ${JSON.stringify(shippingDate)}`)
    }
    if (expressNum != '' && expressNum != undefined) {
        sqlarr.push(`expressNum LIKE '%${expressNum}%'`)
    }
    if (specialtype != '' && specialtype != undefined) {
        sqlarr.push(`specialtype = ${JSON.stringify(specialtype)}`)
    }




    if (sqlarr.length > 0) {
        sqlstr2 += " WHERE " + sqlarr.join(' AND ')
        if (currentpage == 0) {
            sqlstr += " WHERE " + sqlarr.join(' AND ') + ` LIMIT ${pagesize}`;
        } else {
            sqlstr += " WHERE " + sqlarr.join(' AND ') + ` LIMIT ${pagesize} OFFSET ${pagesize * currentpage}`;
        }
    } else {
        if (currentpage == 0) {
            sqlstr += ` LIMIT ${pagesize}`;
        } else {
            sqlstr += ` LIMIT ${pagesize} OFFSET ${pagesize * currentpage}`;
        }
    }
    pool.query(sqlstr, (err, r) => {
        if (err) {
            next(err);
            return;
        } else {
            // res.send({ code: 200, msg: "查询成功", data: r });
            pool.query(sqlstr2, (err2, r2) => {
                if (err2) {
                    //抛出错误，阻止后边程序的执行，用于调试
                    //throw err;
                    //交给下一个错误处理中间件，同时把错误信息传递过去
                    next(err2);
                    //阻止往后执行
                    return;
                }
                res.send({ code: 200, msg: "查询成功", data: r, total: r2.length, pagesize: pagesize, currentpage: currentpage + 1 });
            });
        }
    })


})

// 查询全部订单
r.get('/saveAllOrderlist', (req, res, next) => {
    let userId = req.query.userId;
    let keyword = req.query.keyword;
    let buygoodsDate = req.query.buygoodsDate;
    let shippingDate = req.query.shippingDate;
    let expressNum = req.query.expressNum
    let sqlstr = 'select * from lutian_order'
    let sqlarr = []
    if (keyword != '' && keyword != undefined) {
        sqlarr.push(`(goodsName LIKE '%${keyword}%' OR address LIKE '%${keyword}%' OR logistics LIKE '%${keyword}%' OR storename LIKE '%${keyword}%')`)
    }
    if (userId != '' && userId != undefined) {
        sqlarr.push(`userId = ${userId}`)
    }
    if (buygoodsDate != '' && buygoodsDate != undefined) {
        sqlarr.push(`buygoodsDate = ${JSON.stringify(buygoodsDate)}`)
    }
    if (expressNum != '' && expressNum != undefined) {
        sqlarr.push(`expressNum LIKE '%${expressNum}%'`)
    }
    if (shippingDate != '' && shippingDate != undefined) {
        sqlarr.push(`shippingDate = ${JSON.stringify(shippingDate)}`)
    }



    if (sqlarr.length > 0) {
        sqlstr += " WHERE " + sqlarr.join(' AND ');

    }
    pool.query(sqlstr, (err, r) => {
        if (err) {
            next(err);
            return;
        } else {
            res.send({ code: 200, msg: "查询全部订单成功", data: r });
           
        }
    })


})

// 删除订单
r.get('/deleteorder', (req, res, next) => {
    let goodsId = req.query.goodsId;
    let sqlstr = `delete from lutian_order WHERE goodsId=${goodsId}`
    pool.query(sqlstr, (err, r) => {
        if (err) {
            next(err);
            return;
        } else {
            res.send({ code: 200, msg: "删除成功", data: r });
        }
    })


})

// 修改订单
r.post('/changeorderItem', (req, res, next) => {
    let sqlstr = ''
    let keys = Object.keys(req.body);
    keys.forEach((key, index) => {
        if (key != 'goodsId' && key != 'userId') {
            if (key == 'other' || key == 'buygoodsUrl' || key == 'goodsimg') {
                let jsonString = JSON.stringify(req.body[key]);
                sqlstr += `${key}=${jsonString}`;
            } else {
                sqlstr += `${key}='${req.body[key]}'`;
            }

            // 如果当前不是最后一个字段，添加逗号
            if (index < keys.length - 1) {
                sqlstr += ',';
            }
        }

    });

    const mysql = `update lutian_order set ${sqlstr} WHERE goodsId = ${req.body['goodsId']}`;
    pool.query(mysql, (err, r) => {
        if (err) {
            next(err)
            return;
        } else {
            res.send({ code: 200, msg: '修改成功', data: r });
        }

    })

})






//暴露出去
module.exports = r;